<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :maskClosable="true"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    :title="title"
    :visible="visible"
    :width="width"
    cancelText="关闭"
    destroyOnClose
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-spin :spinning="confirmLoading">
      <template v-if="disableSubmit">
        <a-alert :showIcon="true" style="margin-bottom: 20px;" type="info">
          <div slot="message">
            <a v-if="!showDataSource" @click="() => (showDataSource = !showDataSource)">数据源</a>
            <a v-if="showDataSource" @click="() => (showDataSource = !showDataSource)">返回</a>
          </div>
        </a-alert>
      </template>
      <template v-if="showDataSource">
        <j-code-editor v-if="jsonModel" v-model="jsonModel"></j-code-editor>
      </template>
      <template v-else>
        <a-alert v-if="isImportConfig" :showIcon="true" style="margin-bottom: 20px;" type="info">
          <div slot="message">
            发现相似似告警配置，是否导入
            <a style="margin-left: 24px" @click="$refs.similarModal.visible = true">导入</a>
            <SimilarConfigModel ref="similarModal" :instanceSource="instanceSource" @ok="importConfig" />
          </div>
        </a-alert>
        <a-form-model ref="alarmConfigForm" :label-col="labelCol" :model="model" :wrapper-col="wrapperCol">
          <a-form-model-item v-show="false" ref="id" label="主键" prop="id">
            <a-input v-model="model.id" readOnly />
          </a-form-model-item>
          <a-form-model-item ref="name" :rules="rules.name" label="告警名称" prop="name">
            <a-input v-model="model.name" placeholder="请输入告警名称"></a-input>
          </a-form-model-item>
          <a-form-model-item ref="instanceId" :rules="rules.instanceId" label="设备实例" prop="instanceId">
            <a-tree-select v-model="model.instanceId" :allow-clear="true" :disabled="instanceIdDisable" :tree-data="instanceTreeOptions" :triggers="true" placeholder="请选择设备实例" />
          </a-form-model-item>
          <a-form-model-item ref="triggerMethod" :rules="rules.triggerType" label="触发方式" prop="triggerMethod">
            <a-select v-model="model.triggerMethod" :getPopupContainer="node => node.parentNode">
              <a-select-option key="device">设备触发</a-select-option>
              <a-select-option key="timer">定时检索</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item ref="alarmLevel" :rules="rules.alarmLevel" label="告警等级" prop="alarmLevel">
            <a-radio-group v-model="model.alarmLevel">
              <a-radio-button :value="1">一般</a-radio-button>
              <a-radio-button :value="2">严重</a-radio-button>
              <a-radio-button :value="3">危急</a-radio-button>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item ref="isSave" :rules="rules.isSave" label="是否保存" prop="isSave">
            <a-radio-group v-model="model.isSave">
              <a-radio :value="true">保存</a-radio>
              <a-radio :value="false">不保存</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item ref="isDeal" :rules="rules.isDeal" label="是否处理" prop="isDeal">
            <a-radio-group v-model="model.isDeal">
              <a-radio :value="true">处理</a-radio>
              <a-radio :value="false">不处理</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item v-show="model.triggerMethod === 'timer'" ref="triggerCorn" label="定时表达式" prop="triggerCorn">
            <j-cron v-model="model.corn"></j-cron>
          </a-form-model-item>
          <a-form-model-item v-show="model.triggerMethod" ref="filterKey" label="匹配类型" prop="filterKey">
            <a-radio-group v-model="model.triggerMatchType" size="small">
              <a-radio-button value="any">
                任意(any)
              </a-radio-button>
              <a-radio-button value="all">
                所有(all)
              </a-radio-button>
            </a-radio-group>
          </a-form-model-item>
          <!-- 触发规则 start -->
          <span v-if="model.triggers">
            <a-card v-for="(trigger, triggerIndex) in model.triggers" :key="trigger.id" size="small" style="margin: 10px 0 10px 0">
              <template slot="title">
                <div style="display:flex;align-items:center">
                  <span v-show="!model.triggers[triggerIndex].isNameEdit">{{ model.triggers[triggerIndex].name }}</span>
                  <a v-show="!model.triggers[triggerIndex].isNameEdit" href="javascript:" @click="() => (model.triggers[triggerIndex].isNameEdit = true)">
                    <a-icon style="font-size: 18px; margin-left: 4px" type="edit" />
                  </a>
                  <a-input
                    v-show="model.triggers[triggerIndex].isNameEdit"
                    v-model="model.triggers[triggerIndex].name"
                    style="width:200px"
                    @blur="() => (model.triggers[triggerIndex].isNameEdit = false)"
                  ></a-input>
                  <a v-show="model.triggers[triggerIndex].isNameEdit" href="javascript:" @click="() => (model.triggers[triggerIndex].isNameEdit = false)">
                    <a-icon style="font-size: 18px; margin-left: 4px" type="check" />
                  </a>
                </div>
              </template>
              <template slot="extra">
                <a v-if="model.triggers.length > 1" title="删除触发规则" @click="deleteTrigger(triggerIndex)">
                  <a-icon theme="twoTone" two-tone-color="#eb2f96" type="close-circle" />
                </a>
              </template>
              <template>
                <a-form-model-item v-show="model.triggerMethod" label="消息源">
                  <a-select v-model="model.triggers[triggerIndex].source" :getPopupContainer="node => node.parentNode" placeholder="请选择消息源">
                    <a-select-option v-for="(source, index) in sourceOptions" :key="source.code" :disabled="source.disabled">{{ source.name }} </a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item v-show="model.triggerMethod && model.triggers[triggerIndex].source === 'data_receive'" ref="modelDataId" label="设备数据" prop="modelDataId">
                  <a-select v-model="model.triggers[triggerIndex].modelDataId" :getPopupContainer="node => node.parentNode" @change="val => updateFilterRule(triggerIndex, val)">
                    <a-select-option v-for="(modelData, index) in modelDataOptions" :key="modelData.id"> {{ modelData.name }}({{ modelData.code }}) </a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item v-show="model.triggerMethod" ref="filterValue" label="规则" prop="filterValue">
                  <template>
                    <a-row style="margin-bottom:10px" type="flex">
                      <a-col :span="8">过滤属性</a-col>
                      <a-col :span="7">过滤规则</a-col>
                      <a-col :span="7">过滤值</a-col>
                      <a-col :span="2"></a-col>
                    </a-row>
                    <a-row v-for="(rule, ruleIndex) in model.triggers[triggerIndex].filters" :key="ruleIndex" :gutter="10" style="margin:0;" type="flex">
                      <a-col :span="8">
                        <!-- 过滤器的Key -->
                        <a-form-model-item>
                          <a-select v-model="model.triggers[triggerIndex].filters[ruleIndex].filterKey" :allowClear="true" :getPopupContainer="node => node.parentNode" mode="combobox">
                            <a-select-option v-for="filterKey in model.triggers[triggerIndex].filterRuleOptions" :key="filterKey">
                              {{ filterKey }}
                            </a-select-option>
                          </a-select>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="7">
                        <!-- 过滤器的Rule -->
                        <a-form-model-item>
                          <a-select v-model="model.triggers[triggerIndex].filters[ruleIndex].filterRule" :allowClear="true" :getPopupContainer="node => node.parentNode" placeholder="请选择过滤规则">
                            <a-select-option v-for="option in ruleConditionOptions" :key="option.value">
                              {{ option.text }}
                            </a-select-option>
                          </a-select>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="7">
                        <!-- 过滤器的Value -->
                        <a-form-model-item>
                          <a-input v-model="model.triggers[triggerIndex].filters[ruleIndex].filterValue" :allowClear="true" placeholder="请输入过滤值" />
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="2">
                        <a-form-model-item>
                          <a title="删除规则条件" @click="delRowRule(triggerIndex, ruleIndex)">
                            <a-icon theme="twoTone" two-tone-color="#eb2f96" type="close-circle" />
                          </a>
                        </a-form-model-item>
                      </a-col>
                    </a-row>
                    <a-row>
                      <a @click="addRowRule(triggerIndex)">
                        <a-icon type="plus" />
                        新增规则
                      </a>
                    </a-row>
                  </template>
                </a-form-model-item>
              </template>
            </a-card>
          </span>
          <a href="#" style="margin: 10px 0 10px 0" @click="addTrigger">
            <a-icon style="font-size: 18px; margin-right: 4px" type="plus" />
            新增触发规则
          </a>
          <!-- 触发规则 end -->

          <!-- 执行器 start -->
          <a-card v-for="(actuator, actuatorIndex) in model.actuators" v-if="model.actuators" :key="actuator.id" size="small" style="margin: 10px 0 10px 0">
            <!-- 执行器标题 -->
            <template slot="title">
              <div style="display:flex;align-items:center">
                <span v-show="!actuator.isNameEdit">{{ actuator.name }}</span>
                <a v-show="!actuator.isNameEdit" href="javascript:" @click="() => (actuator.isNameEdit = true)">
                  <a-icon style="font-size: 18px; margin-left: 4px" type="edit" />
                </a>
                <a-input v-show="actuator.isNameEdit" v-model="actuator.name" style="width:200px" @blur="() => (actuator.isNameEdit = false)"></a-input>
                <a v-show="actuator.isNameEdit" href="javascript:" @click="() => (actuator.isNameEdit = false)">
                  <a-icon style="font-size: 18px; margin-left: 4px" type="check" />
                </a>
              </div>
            </template>
            <!-- 按钮：删除执行器 -->
            <template slot="extra">
              <a v-if="model.actuators.length > 1" title="删除执行器" @click="deleteActuator(actuatorIndex)">
                <a-icon theme="twoTone" two-tone-color="#eb2f96" type="close-circle" />
              </a>
            </template>
            <!-- 执行类型 -->
            <a-form-model-item v-if="model.triggerMethod" :prop="'actuators.' + actuatorIndex + '.actuatorType'" :rules="[{ required: true, message: '请选择执行类型!' }]" label="执行类型">
              <a-select v-model="actuator.actuatorType" :getPopupContainer="node => node.parentNode" allowClear placeholder="请选择执行类型">
                <a-select-option v-for="actuatorType in actuatorTypeOptions" :key="actuatorType.value">{{ actuatorType.text }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <!-- 消息通知 -->
            <template>
              <!-- 通知类型 -->
              <a-form-model-item
                v-if="model.triggerMethod && actuator.actuatorType === 1"
                :prop="'actuators.' + actuatorIndex + '.notification.noticeType'"
                :rules="[
                  {
                    required: model.triggerMethod && actuator.actuatorType === 1,
                    message: '请选择通知类型!'
                  }
                ]"
                label="通知类型"
              >
                <a-select v-model="actuator.notification.noticeType" :getPopupContainer="node => node.parentNode" allowClear placeholder="请选择通知类型">
                  <template v-for="noticeTypeOpt in noticeTypeOptions">
                    <a-select-option :key="noticeTypeOpt.value" :disabled="noticeTypeOpt.disabled">{{ noticeTypeOpt.text }}</a-select-option>
                  </template>
                </a-select>
              </a-form-model-item>
              <!-- 通知配置 -->
              <a-form-model-item
                v-if="model.triggerMethod && actuator.actuatorType === 1 && actuator.notification.noticeType"
                :prop="'actuators.' + actuatorIndex + '.notification.noticeConfigId'"
                :rules="[
                  {
                    required: model.triggerMethod && actuator.actuatorType === 1 && actuator.notification.noticeType,
                    message: '请选择通知配置!'
                  }
                ]"
                label="通知配置"
              >
                <a-select v-model="actuator.notification.noticeConfigId" :getPopupContainer="node => node.parentNode" allowClear placeholder="请选择通知配置">
                  <a-select-option v-for="noticeConfig in noticeConfigOptions" :key="noticeConfig.id">
                    {{ noticeConfig.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <!-- 通知模板 -->
              <a-form-model-item
                v-if="model.triggerMethod && actuator.actuatorType === 1"
                :prop="'actuators.' + actuatorIndex + '.notification.noticeTemplateCode'"
                :rules="[
                  {
                    required: model.triggerMethod && actuator.actuatorType === 1,
                    message: '请选择通知模板!'
                  }
                ]"
                label="通知模板"
              >
                <a-select v-model="actuator.notification.noticeTemplateCode" :getPopupContainer="node => node.parentNode" placeholder="请选择通知模板">
                  <a-select-option v-for="noticeTemplate in noticeTemplates" :key="noticeTemplate.code">{{ noticeTemplate.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </template>
            <!-- 功能调用 -->
            <template v-if="model.triggerMethod && actuator.actuatorType === 2">
              <!-- 设备选择 -->
              <a-form-model-item
                :prop="'actuators.' + actuatorIndex + '.invokeFunction.instanceId'"
                :rules="[
                  {
                    required: model.triggerMethod && actuator.actuatorType === 2,
                    message: '请选择设备实例!'
                  }
                ]"
                label="设备选择"
              >
                <a-tree-select
                  defaultValue=""
                  v-if="actuator.invokeFunction.instanceId"
                  v-model="actuator.invokeFunction.instanceId"
                  :allow-clear="true"
                  :tree-data="instanceTreeOptions"
                  :triggers="true"
                  placeholder="请选择设备实例"
                />
              </a-form-model-item>
              <!-- 设备功能  -->
              <a-form-model-item
                :prop="'actuators.' + actuatorIndex + '.invokeFunction.functionId'"
                :rules="[
                  {
                    required: model.triggerMethod && actuator.actuatorType === 2,
                    message: '请选择设备功能!'
                  }
                ]"
                label="设备功能"
              >
                <a-select
                  v-model="actuator.invokeFunction.functionId"
                  :getPopupContainer="node => node.parentNode"
                  allowClear
                  placeholder="请选择设备功能"
                  @change="val => updateFunctionParams(actuatorIndex, val)"
                >
                  <a-select-option v-for="option in model.actuators[actuatorIndex].invokeFunction.functionOptions" :key="option.funcId">{{ option.funcName }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <!--  功能参数  -->
              <a-form-model-item label="功能参数">
                <span v-if="functionOption.funcId === actuator.invokeFunction.functionId">
                  <a-card v-for="functionOption in model.actuators[actuatorIndex].invokeFunction.functionOptions" :key="functionOption.id" size="small">
                    <a-form-model-item v-for="param in functionOption.inputParams" :key="param.id" :label="param.name">
                      <a-input v-model="param.value" :disabled="param.inputMode === 'ins_input'" />
                    </a-form-model-item>
                  </a-card>
                </span>
              </a-form-model-item>
            </template>
            <!-- 数据转发 -->
            <template v-if="model.triggerMethod && actuator.actuatorType === 3">
              <!--              <a-form-model-item>-->
              <!--                <a-radio-group v-model="actuator.dataForward.forwordType" @change="">-->
              <!--                  <a-radio value="push">推送</a-radio>-->
              <!--                  <a-radio value="request">请求</a-radio>-->
              <!--                </a-radio-group>-->
              <!--              </a-form-model-item>-->
              <a-form-model-item
                :prop="'actuators.' + actuatorIndex + '.dataForward.networkServiceId'"
                :rules="[
                  {
                    required: model.triggerMethod && actuator.actuatorType === 3,
                    message: '请选择网络服务!'
                  }
                ]"
                label="网络服务"
              >
                <a-select v-if="actuator.dataForward" v-model="actuator.dataForward.networkServiceId" :getPopupContainer="node => node.parentNode" allowClear placeholder="请选择网络服务">
                  <a-select-option v-for="option in networkOptions" :key="option.id">{{ option.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item
                :prop="'actuators.' + actuatorIndex + '.dataForward.forwardReceivers'"
                :rules="[
                  {
                    required: model.triggerMethod && actuator.actuatorType === 3,
                    message: '请选择网络客户端!'
                  }
                ]"
                label="网络客户端"
              >
                <a-select
                  v-if="actuator.dataForward"
                  v-model="actuator.dataForward.forwardReceivers"
                  :default-value="[]"
                  :getPopupContainer="node => node.parentNode"
                  mode="multiple"
                  style="width: 100%"
                  placeholder="请选择网络客户端"
                  @change=""
                  allowClear
                >
                  <a-select-option v-for="option in actuator.dataForward.networkReceiverOptions" :key="option.socketAddress">{{ option.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item
                :prop="'actuators.' + actuatorIndex + '.dataForward.forwardReceiver'"
                :rules="[
                  {
                    required: false
                  }
                ]"
                label="转发数据"
              >
                <j-code-editor v-model="model.data"></j-code-editor>
              </a-form-model-item>
            </template>
          </a-card>
          <a href="#" style="margin: 10px 0 10px 0" @click="addActuator">
            <a-icon style="font-size: 18px; margin-right: 4px" type="plus" />
            新增执行动作
          </a>
          <!-- 执行器 end -->
          <a-form-model-item ref="description" label="说明" prop="description">
            <a-textarea v-model="model.description" placeholder="请输入说明" rows="4" />
          </a-form-model-item>
        </a-form-model>
      </template>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import JCron from '@/components/jeecg/JCron'
import SimilarConfigModel from './SimilarConfigModel'
import JCodeEditor from '@comp/jeecg/JCodeEditor'

export default {
  name: 'DeviceAlarmConfigModal',
  components: {
    JCodeEditor,
    SimilarConfigModel,
    JSearchSelectTag,
    JCron
  },
  computed: {
    configName() {
      return this.model.configName
    },
    instanceId() {
      return this.model.instanceId
    },
    triggerMethod() {
      return this.model.triggerMethod
    },
    triggers() {
      return this.model.triggers
    },
    actuators() {
      return JSON.stringify(this.model.actuators)
    }
  },
  watch: {
    instanceId(val, oval) {
      console.log('watch-instanceId', oval, '=>', val)
      if (val) {
        if (!this.disableSubmit) {
          this.querySimilarConfig(val)
        }
        this.loadModelDatas(val)
      } else {
        this.isImportConfig = false
      }
    },
    triggerMethod(val, oval) {
      let scoped = this
      console.log('watch-triggerMethod', oval, '=>', val)
      if (val) {
        if (val === 'timer') {
          for (let trigger of this.model.triggers) {
            trigger.source = 'data_receive'
            scoped.sourceOptions
              .filter(sourceOption => sourceOption.code !== 'data_receive')
              .map(sourceOption => {
                sourceOption['disabled'] = true
              })
          }
        } else {
          for (let trigger of this.model.triggers) {
            scoped.sourceOptions.map(sourceOption => {
              sourceOption['disabled'] = false
            })
          }
        }
      }
    },
    triggers: {
      handler(val, oval) {
        console.log('watch-triggers', oval, '=>', val)
        if (!oval && val) {
          for (let i = 0; i < val.length; i++) {
            // 表单加载时
            console.log('watch-triggers[' + i + ']', oval, '=>', val[i])
            /* 定时判断this.modelDataOptions的长度 */
            let timer = window.setInterval(() => {
              if (this.modelDataOptions.length > 0) {
                this.updateFilterRule(i, val[i].modelDataId)
                window.clearInterval(timer)
              }
            }, 100)
          }
        }
      }
    },
    actuators: {
      handler(val, oval) {
        let scope = this
        if (oval !== val) {
          // let oval_ = JSON.parse(oval || '')
          let val_ = JSON.parse(val)
          for (let i = 0; i < val_.length; i++) {
            // 表单加载时
            console.log('watch-actuators -> ' + val_[i].actuatorType)
            // 功能调用时
            if (val_[i].actuatorType === 2) {
              val_[i].invokeFunction = Object.assign(JSON.parse(JSON.stringify(this.baseModel.actuators[0].invokeFunction)), val_[i].invokeFunction)
              console.log('invokeFunction -> ', i, val_[i].invokeFunction)
              this.updateDeviceFunction(i, val_[i].invokeFunction.instanceId)
            }
            // 消息通知
            else if (val_[i].actuatorType === 1) {
              if (val_[i].notification) {
                this.noticeTypeChanged(val_[i].notification.noticeType)
              }
            }
            // 数据转发
            else if (val_[i].actuatorType === 3) {
              this.getNetwork()
              val_[i].dataForward = Object.assign(JSON.parse(JSON.stringify(this.baseModel.actuators[0].dataForward)), val_[i].dataForward)
              this.networkServiceChanged(val_[i].dataForward.networkServiceId, i)
              console.log(val_[i].dataForward)
            }
          }
          scope.$forceUpdate()
        }
      },
      deep: true,
      // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
      immediate: true
    }
  },
  data() {
    return {
      title: '操作',
      width: 800,
      visible: false,
      disableSubmit: false,
      instanceIdDisable: false,
      instanceTreeOptions: [],
      sourceOptions: [],
      ruleConditionOptions: [],
      modelDataOptions: [],
      actuatorTypeOptions: [],
      noticeTypeOptions: [],
      noticeConfigOptions: [],
      deviceFunctionOptions: [],
      functionInputParams: [],
      instanceSource: [],
      noticeTemplates: [],
      networkOptions: [],
      showDataSource: false,
      baseModel: {
        instanceId: '',
        alarmLevel: 1,
        isDeal: false,
        triggerMatchType: 'any',
        triggers: [
          {
            name: '触发规则1',
            isNameEdit: false,
            filters: [{}],
            filterRuleOptions: []
          }
        ],
        actuators: [
          {
            name: '执行动作1',
            isNameEdit: false,
            actuatorType: '',
            notification: {
              noticeConfig: '',
              noticeType: '',
              noticeConfigId: '',
              noticeTemplateCode: ''
            },
            invokeFunction: {
              instanceId: '',
              functionId: '',
              functionOptions: [],
              params: [{ dataId: '', value: '' }]
            },
            dataForward: {
              forwardType: 'push', // request
              networkServiceId: '',
              forwardReceivers: [],
              networkReceiverOptions: []
            }
          }
        ]
      },
      isImportConfig: false,
      jsonModel: '',
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      rules: {
        name: [
          { required: true, message: '请输入告警名称!' },
          { min: 3, max: 30, message: '实例告警长度为3-30个字符' }
        ],
        instanceId: [{ required: true, message: '请选择设备实例!' }],
        triggerType: [{ required: true, message: '请选择触发方式!' }]
      },
      url: {
        add: 'alarm/config/add',
        edit: 'alarm/config/edit',
        getConfigForm: 'alarm/config/queryWholeById',
        instanceTree: 'device/instance/listTree',
        getSources: 'alarm/trigger/listMessageEventType',
        getRuleCondition: 'alarm/trigger/listRuleCondition',
        getModelDatas: 'device/model/queryDataByInstanceId',
        getActuatorType: 'alarm/config/getActuatorType',
        getNoticeConfig: 'alarm/config/getNoticeConfig',
        getNoticeType: 'alarm/config/getNoticeType',
        getFunction: 'device/instance/getExtendParams'
      }
    }
  },
  mounted() {
    this.loadInstances()
    this.loadSources()
    this.getRuleCondition()
    this.getActuatorType()
    this.getNoticeConfig()
    this.getNoticeType()
    // this.$forceUpdate()
  },
  methods: {
    networkServiceChanged(networkServiceId, actuatorIndex) {
      this.getNetworkClient(networkServiceId, actuatorIndex)
    },
    getNetworkClient(networkServiceId, actuatorIndex) {
      let scope = this
      getAction('/network/manage/listConnectById', { id: networkServiceId }).then(data => {
        if (data.success) {
          scope.model.actuators[actuatorIndex].dataForward.networkReceiverOptions = data.result.map(network => {
            return {
              socketAddress: network.socketAddress,
              name: network.instance.name
            }
          })
          scope.$forceUpdate()
        }
      })
    },
    importConfig(configId) {
      this.edit({ id: configId }, this.model.id, this.model.instanceId)
    },
    // 查询相似配置
    querySimilarConfig(instanceId) {
      let score = this
      getAction(`/alarm/config/querySameLevelByInstanceId/${instanceId}`).then(data => {
        console.log('相似配置', data.result)
        if (data.success) {
          if (data.result.length > 0) {
            score.isImportConfig = true
            score.instanceSource = data.result
          } else {
            score.isImportConfig = false
          }
        }
      })
    },
    updateFunctionParams(actuatorIndex, functionId) {
      //   let scope = this
      //   if (functionId) {
      //     this.functionInputParams =
      //       this.model.actuators[actuatorIndex].invokeFunction.functionOptions.filter(func => func.funcId === functionId)[0].inputParams
      //   }
      //   this.functionInputParams.map((param, index) => {
      //     console.log(param.name, index)
      //     console.log(this.model.actuators[actuatorIndex].invokeFunction.params)
      //     if(!this.model.actuators[actuatorIndex].invokeFunction.params[index]){
      //       this.model.actuators[actuatorIndex].invokeFunction.params.push({dataId: '', value:''})
      //     }
      //     console.log(this.model.actuators[actuatorIndex].invokeFunction.params[index]['dataId'], param.id)
      //     this.model.actuators[actuatorIndex].invokeFunction.params[index]['dataId'] = param.id
      //     this.model.actuators[actuatorIndex].invokeFunction.params[index]['value'] = param.value
      //   })
    },
    updateDeviceFunction(actuatorIndex, instanceId) {
      let scope = this
      if (!instanceId) {
        console.log(`instanceId is null`)
      }
      getAction(this.url.getFunction, { id: instanceId }).then(res => {
        if (res.success) {
          scope.model.actuators[actuatorIndex].invokeFunction.functionOptions = res.result
          scope.$forceUpdate()
        }
      })
    },
    updateFilterRule(triggerIndex, modelDataId) {
      console.log(`updateFilterRule(${triggerIndex}, ${modelDataId})`)
      this.model.triggers[triggerIndex].filterRuleOptions = []
      let modelDatas = this.modelDataOptions.filter(data => data.id === modelDataId)
      console.log(modelDatas)
      if (modelDatas.length > 0) {
        let currentModelData = modelDatas[0]
        let dataType = currentModelData.type
        if ('vector3'.indexOf(dataType) !== -1) {
          // 对象处理
          this.model.triggers[triggerIndex].filterRuleOptions.push(`${currentModelData.code}.x`)
          this.model.triggers[triggerIndex].filterRuleOptions.push(`${currentModelData.code}.y`)
          this.model.triggers[triggerIndex].filterRuleOptions.push(`${currentModelData.code}.z`)
        } else {
          // 单个数据
          this.model.triggers[triggerIndex].filterRuleOptions.push(currentModelData.code)
        }
        this.$forceUpdate()
      }
      console.log(this.model.triggers[triggerIndex].filterRuleOptions)
    },
    getNoticeConfig() {
      let scope = this
      getAction(this.url.getNoticeConfig).then(res => {
        if (res.success) {
          scope.noticeConfigOptions = res.result
        }
      })
    },
    getNoticeType() {
      let scope = this
      getAction(this.url.getNoticeType).then(res => {
        if (res.success) {
          scope.noticeTypeOptions = res.result.map(type => {
            type['disabled'] = !(type.value === 4 || type.value === 6)
            return type
          })
        }
      })
    },
    getActuatorType() {
      let scope = this
      getAction(this.url.getActuatorType).then(res => {
        if (res.success) {
          scope.actuatorTypeOptions = res.result
        }
      })
    },
    noticeTypeChanged(type) {
      this.getSysMsgTemplate(type)
    },
    // 获取网络服务配置列表
    getNetwork() {
      let scope = this
      getAction('/network/manage/listAll').then(data => {
        if (data.success) {
          scope.networkOptions = data.result
        }
      })
    },
    getSysMsgTemplate(tempType) {
      console.log('消息类型', tempType, JSON.stringify(this.noticeTemplates[tempType]))
      let scope = this
      getAction(`alarm/config/querySysMsgTemplate/${tempType}`).then(data => {
        if (data.success) {
          scope.noticeTemplates = data.result
        }
      })
    },
    addRowRule(triggerIndex) {
      this.model.triggers[triggerIndex].filters.push({})
      this.$forceUpdate()
    },
    delRowRule(triggerIndex, ruleIndex) {
      console.log(ruleIndex)
      this.model.triggers[triggerIndex].filters.splice(ruleIndex, 1)
      this.$forceUpdate()
    },
    loadModelDatas(instanceId) {
      let scoped = this
      getAction(this.url.getModelDatas, { instanceId: instanceId }).then(res => {
        if (res.success) {
          scoped.modelDataOptions = res.result
        }
      })
    },
    loadSources() {
      let scoped = this
      getAction(this.url.getSources).then(res => {
        if (res.success) {
          scoped.sourceOptions = res.result.filter(source => source.code.indexOf('network') === -1)
        }
      })
    },
    getRuleCondition() {
      let scoped = this
      getAction(this.url.getRuleCondition).then(res => {
        if (res.success) {
          scoped.ruleConditionOptions = res.result
        }
      })
    },
    addTrigger() {
      this.model.triggers.push({
        name: '触发规则' + (this.model.triggers.length + 1),
        isNameEdit: false,
        filters: [{}]
      })
    },
    deleteTrigger(triggerIndex) {
      this.model.triggers.splice(triggerIndex - 0, 1)
      this.model.triggers.forEach((trigger, index) => {
        if (parseFloat(trigger.name.substr(trigger.name.length - 1, 1)).toString() !== 'NaN') {
          trigger.name = trigger.name.substring(0, trigger.name.length - 1) + (index + 1)
        }
      })
    },
    addActuator() {
      let baseModel = JSON.parse(JSON.stringify(this.baseModel))
      this.model.actuators.push(
        Object.assign(baseModel.actuators[0], {
          name: '执行动作' + (this.model.actuators.length + 1),
          isNameEdit: false
        })
      )
    },
    deleteActuator(actuatorIndex) {
      this.model.actuators.splice(actuatorIndex - 0, 1)
      this.model.actuators.forEach((actuator, index) => {
        if (parseFloat(actuator.name.substr(actuator.name.length - 1, 1)).toString() !== 'NaN') {
          actuator.name = actuator.name.substring(0, actuator.name.length - 1) + (index + 1)
        }
      })
    },
    loadInstances() {
      getAction(this.url.instanceTree).then(res => {
        if (res.success) {
          this.instanceTreeOptions = res.result
        }
      })
    },
    add(instanceId) {
      this.model = JSON.parse(JSON.stringify(this.baseModel))
      this.model['instanceId'] = instanceId
      console.log(this.model)
      if (!instanceId) {
        this.instanceIdDisable = false
      }
      this.visible = true
    },
    detail(configId) {
      this.disableSubmit = true
      this.edit(configId)
    },
    edit(configId, oldId = undefined, oldInstanceId = undefined) {
      let scope = this
      if (!configId) {
        return
      }
      getAction(this.url.getConfigForm, { id: configId }).then(res => {
        if (res.success) {
          // 数据转发：接收者字符串类型根据逗号分割成数组
          res.result.actuators
            .filter(actuator => actuator.actuatorType === 3)
            .map(actuator => {
              actuator.dataForward.forwardReceivers = actuator.dataForward.forwardReceivers.split(',')
            })
          scope.model = Object.assign({}, res.result)
          let baseModel = JSON.parse(JSON.stringify(scope.baseModel))
          scope.model.triggers.map(trigger => {
            Object.assign(baseModel.triggers[0], trigger)
          })
          scope.model.actuators.map(actuator => {
            Object.assign(baseModel.actuators[0], actuator)
          })

          // 导入时，使用原始实例id
          if (oldInstanceId) {
            scope.model.instanceId = oldInstanceId
            scope.model.id = oldId
          }
          if (scope.disableSubmit) {
            // 查看时，格式化model为json
            scope.jsonModel = JSON.stringify(scope.model, null, '\t')
          }
          console.log(scope.model)
        }
      })
      this.visible = true
    },
    close() {
      this.model = {}
      this.isImportConfig = false
      if (!this.disableSubmit) {
        this.$refs.alarmConfigForm.resetFields()
      } else {
        this.jsonModel = ''
      }
      this.$emit('close')
      this.visible = false
      this.disableSubmit = false
      this.confirmLoading = false
      this.$forceUpdate()
    },
    handleOk() {
      const self = this
      // 触发表单验证
      this.$refs.alarmConfigForm.validate(valid => {
        if (valid) {
          self.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }

          // 从functionOptions中过滤出具体功能参数
          this.model.actuators
            .filter(actuator => actuator.actuatorType === 2)
            .map(actuator =>
              actuator.invokeFunction.functionOptions
                .filter(funcOption => funcOption.funcId === actuator.invokeFunction.functionId)
                .map(func =>
                  func.inputParams.map((param, index) => {
                    actuator.invokeFunction.params[index] = {
                      dataId: param.id,
                      value: param.value
                    }
                  })
                )
            )
          // 过滤多余执空的行动作
          this.model.actuators
            .filter(actuator => actuator.actuatorType === 3)
            .map(actuator => {
              if (actuator.actuatorType === 1) {
                return actuator.notification
              } else if (actuator.actuatorType === 2) {
                return actuator.invokeFunction
              } else if (actuator.actuatorType === 3) {
                // 数据转发：接收者数组类型根据逗号转成字符串
                actuator.dataForward.forwardReceivers = actuator.dataForward.forwardReceivers.join(',')
                return actuator.dataForward
              }
              return {}
            })

          console.log(this.model)

          httpAction(httpurl, this.model, method)
            .then(res => {
              if (res.success) {
                self.$message.success(res.message)
                self.$emit('ok')
              } else {
                self.$message.warning(res.message)
              }
            })
            .finally(() => {
              self.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style scoped>
.trigger-name {
}
</style>
